import { Upload, Button, message } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { useState } from 'react';

const WatermarkRemover = () => {
  const [imageUrl, setImageUrl] = useState<string>();
  const [loading, setLoading] = useState(false);

  const handleUpload = async (file: File) => {
    setLoading(true);
    const formData = new FormData();
    formData.append('image', file);

    try {
      const response = await fetch('http://localhost:3001/api/remove-watermark', {
        method: 'POST',
        body: formData,
      });
      
      if (response.ok) {
        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);
        setImageUrl(url);
        message.success('水印去除成功！');
      } else {
        message.error('水印去除失败，请重试！');
      }
    } catch (error) {
      message.error('水印去除失败，请重试！');
    } finally {
      setLoading(false);
    }
  };

  const handleDownload = () => {
    if (imageUrl) {
      const a = document.createElement('a');
      a.href = imageUrl;
      a.download = 'watermark_removed.png';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    }
  };

  return (
    <div style={{ textAlign: 'center', padding: '20px' }}>
      <h2>去除图片水印</h2>
      <div style={{ marginBottom: '20px' }}>
        <Upload
          customRequest={({ file }) => handleUpload(file as File)}
          showUploadList={false}
          accept="image/*"
        >
          <Button icon={<UploadOutlined />} loading={loading}>
            选择图片
          </Button>
        </Upload>
      </div>
      {imageUrl && (
        <div>
          <img
            src={imageUrl}
            alt="处理后的图片"
            style={{ maxWidth: '100%', marginBottom: '20px' }}
          />
          <Button type="primary" onClick={handleDownload}>
            下载处理后的图片
          </Button>
        </div>
      )}
      <p style={{ marginTop: '20px' }}>
        支持JPG、PNG等格式，文件大小限制为20MB
      </p>
    </div>
  );
};

export default WatermarkRemover; 